# -*- coding: utf-8  -*-
#    Small Public Domain Bot - A Python bot that uses Pywikipediabot framework and works on MediaWiki wikis at general.
#    Copyright (C) 2008 OsamaK
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#    Please report bugs or help imporving this program by connecting to <OsamaK.WFM@gmail.com>
import wikipedia
import timefrom okbot import *

targetCategory = raw_input("You want to scan the category.. (default:User-created public domain images) ")
if not targetCategory: targetCategory= 'User-created_public_domain_images'

targetWiki=raw_input("In (en\\commons).. ")
if targetWiki == 'en' or not targetWiki: site = wikipedia.getSite(code='en',fam='wikipedia')
elif targetWiki == 'commons':
  site = wikipedia.getSite(code='commons',fam='commons')

def main():
  timenum = 0
  while True:
    if timenum == 0:
      cmcontinue = smallpd()
    else:
      cmcontinue = smallpd(cmcontinue)
    timenum = 1
    wikipedia.output("Sleep for 10 seconds.")
    time.sleep(10) # Can be changed freely.

def smallpd(cmcontinue='!|'):
  #reportfile = open("../public_html/newsmallpd",'a') #For the [[m:toolserver]]
  reportfile = open("largfu",'a') #For PC usage.
  #http://en.wikipedia.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:User-created_public_domain_images&cmnamespace=6&cmcontinue=Shervin|&cmlimit=50&format=jsonfm
  predata = {
             'action': 'query',
             'list': 'categorymembers',
             'cmtitle': 'Category:' + targetCategory,
             'cmnamespace': '6',
             'cmcontinue': cmcontinue,
             'cmprop': 'title',
             'cmlimit': '200',
             'format': 'json',
              }
  data = getAPI(site, predata)
  if data == None: return cmcontinue # Was there any error?
  try:
    cmcontinue = data['query-continue']['categorymembers']['cmcontinue']
  except: return cmcontinue

  for page in data['query']['categorymembers']:
    title = unicode(page['title'])
    if title.lower().endswith("ogg") or title.lower().endswith("mid") or title.lower().endswith("pdf"): continue

    predata = {#http://en.wikipedia.org/w/api.php?action=query&list=imageusage&iutitle=title&format=jsonfm
               'action': 'query',
               'list': 'imageusage',
               'iutitle': title,
               'format': 'json',
              }
    usagedata = getAPI(site, predata)
    if usagedata == None: return cmcontinue
    if len(usagedata['query']['imageusage']) == 0:
      wikipedia.output("%s is orphaned!" % title)
    else:
      time.sleep(0.5)
      wikipedia.output("%s IS NOT ORPHANED!" % title)
      continue
    predata = {#http://en.wikipedia.org/w/api.php?action=query&titles=Image:Where%20in%20world%20is%20osama.jpg&prop=imageinfo&iiprop=size&format=jsonfm
               'action': 'query',
               'prop': 'imageinfo',
               'titles': title,
               'iiprop':'size',
               'format': 'json',
              }
    sizedata = getAPI(site, predata)
    if sizedata == None: return cmcontinue
    for imageid in sizedata['query']['pages']:
      if not sizedata['query']['pages'][imageid].has_key('imageinfo'): continue
      width = sizedata['query']['pages'][imageid]['imageinfo'][0]['width']
      height = sizedata['query']['pages'][imageid]['imageinfo'][0]['height']

      if width <= 100 and height <= 100:
        wikipedia.output(u"%s's size is %s × %s! It is small." % (title,width,height))
        reportfile.write(u"%s|[[:%s]] (%s × %s)\n".encode('utf-8') % (title.encode('utf-8'), title.encode('utf-8'), width, height))
      else:
        wikipedia.output(u"%s's size is %s × %s, big enough." % (title,width,height))
    time.sleep(0.5)
  reportfile.close()
  return cmcontinue

if __name__ == '__main__':
    try:
        main()
    finally:
        wikipedia.stopme()
